<script setup>
import {defineProps,computed,ref, defineEmits} from "vue";
import router from "@/router/index.js"
import {
  RequestDeleteJob,
  RequestSubmitHunyuanModelJobByText,
  RequestSubmitHunyuanModelJobByImage,
  RequestSubmitRetryJob
} from "@/api/Hunyuan.js"
import {ElMessage, ElMessageBox} from "element-plus";

const props = defineProps({
  jobData: {
    type: Object,
    default: () => {
      return null;
    }
  }
});

const emit = defineEmits(["onDelete","retryJob", "cardClicked"]);

// 模型预览图片
const modelPreviewImageUrls = computed(() => {
  let urls = [];
  if(!props.jobData || !props.jobData.resultFile3Ds){
    return urls;
  }
  props.jobData.resultFile3Ds.forEach(file=>{
    if(file.localPreviewImagePath && file.localPreviewImagePath.length>7){
      urls.push(file.localPreviewImagePath);
    }else if(file.tencentPreviewImageUrl && file.tencentPreviewImageUrl.length>7){
      urls.push(file.tencentPreviewImageUrl);
    }else{
    }
  });
  return urls;
})

// 跳转到模型查看页面
function toModelShowView(){
  console.log("跳转到模型查看页面",props.jobData.resultFile3Ds[0].localFilePath,props.jobData.resultFile3Ds[0].localMaterialPath)
  router.push({
    name: "modelShowView",
    query: {
      objUrl: props.jobData.resultFile3Ds[0].localFilePath,
      mtlUrl: props.jobData.resultFile3Ds[0].localMaterialPath ? props.jobData.resultFile3Ds[0].localMaterialPath : "",
    }
  })
}

// 加载动画与图标
const loading = ref(true);
const loadingSvg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `

// 详情页是否展示
const dialogDetailVisible = ref(false);
// 打开详情页
function openModelDialogDetail(){
  dialogDetailVisible.value = true;
}

// 格式化时间
function formatDateTime(dateStr) {
  const date = new Date(dateStr);

  // 验证日期有效性
  if (isNaN(date.getTime())) {
    throw new Error('Invalid date string');
  }

  const year = date.getFullYear();
  const month = date.getMonth() + 1;  // getMonth() 返回 0-11
  const day = date.getDate();
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');

  return `${year}年${month}月${day}日 ${hour}:${minute}:${second}`;
}

// 删除任务
async function deleteJob(){
  try {
    let res = await RequestDeleteJob(props.jobData.id);
    if(res.data.code === 200){
      ElMessage.success("删除任务成功");
      emit("onDelete",props.jobData.id);
    }
  } catch (e) {
    console.log("删除任务出错",e);
    ElMessage.error("删除任务出错"+e);
  }
}

// 删除按钮
function handleClose(){
  ElMessageBox.confirm(
      '你确定要删除此模型任务吗?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
        deleteJob();
  });
}

/**
 * 重试生成模型
 */
async function retryGen3DModel(){
  ElMessageBox.confirm(
      '你确定要重新生成此模型任务吗?',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      const res = await RequestSubmitRetryJob(props.jobData.id);
      if (res.data.code === 200) {
        props.jobData.status = 0;
        ElMessage.success("重试生成模型成功");
      }
    } catch (e) {
      console.log("重试生成模型失败", e)
    }
  });


}


</script>

<template>
  <div>
    <div class="model-card-wrapper" @click="$emit('cardClicked', props.jobData)">
      <!-- 新增关闭按钮 -->
      <div class="closeBtn" @click.stop="handleClose">
        <el-icon><Close /></el-icon>
      </div>

      <div>
        <!--任务为生成成功状态-->
        <div v-if="(jobData.status === 3 || jobData.status === 5) && modelPreviewImageUrls.length>0">
          <el-image
              class="showCard"
              :src="modelPreviewImageUrls[0]"
              :preview-src-list="modelPreviewImageUrls"
          ></el-image>
        </div>
        <!-- 等待中 -->
        <div v-else-if="jobData.status === 0" class="showCard cardCenter">
          <div>
            等待中...
          </div>
        </div>
        <!--执行中-->
        <div v-else-if="jobData.status === 1">
          <el-card
              class="showCard"
              style="border:none;min-height:200px;"
              v-loading="loading"
              :element-loading-svg="loadingSvg"
              element-loading-svg-view-box="-10, -10, 50, 50"
              shadow="never"
              element-loading-text="生成中"
          ></el-card>
        </div>

        <!--任务失败-->
        <div v-else-if="jobData.status === 2 || modelPreviewImageUrls.length===0" class="showCard">
          <br/>
          <el-result
              icon="error"
              title="生成失败"
          >
            <template #extra>
              <el-button type="primary" link @click="retryGen3DModel">重试</el-button>
            </template>
          </el-result>
        </div>
        <!--下载失败-->
        <div v-else-if="jobData.status === 4" class="showCard">
          <br/>
          <el-result
              icon="warning"
              title="生成成功，但下载失败"
          >
            <template #extra>
              <el-button type="primary" link>重试</el-button>
            </template>
          </el-result>
        </div>
        <div v-else>
          {{jobData}}
          <br/>
          {{jobData.status}}
        </div>
      </div>

      <div class="viewBtn">
        <el-button type="default" @click="openModelDialogDetail">查看详情</el-button>
        <el-button type="primary" v-if="jobData.status===5 && modelPreviewImageUrls.length!==0" @click="toModelShowView">查看模型</el-button>
      </div>
    </div>

    <div>
      <!-- 任务详情页 -->
      <!-- 任务详情页 -->
      <el-dialog v-model="dialogDetailVisible" title="模型详情" width="800px" :align-center="false">
        <el-descriptions
            :column="1"
            :size="'large'"
            border
            class="job-details-descriptions"
            :label-width="100"
        >
          <!-- 任务ID -->
          <el-descriptions-item label="任务ID">
            <code style="font-size: 14px; color: #e91e63;">{{ jobData.jobId }}</code>
          </el-descriptions-item>

          <!-- 任务状态 -->
          <el-descriptions-item label="状态">
            <el-tag
                :type="
          jobData.status === 0 ? 'info' :
          jobData.status === 1 ? 'warning' :
          (jobData.status === 2 || modelPreviewImageUrls.length === 0) ? 'danger' :
          jobData.status === 4 ? 'warning' :
          'success'
        "
                size="large"
            >
              {{
                jobData.status === 0 ? '等待中' :
                    jobData.status === 1 ? '执行中' :
                        jobData.status === 2 ? '生成失败' :
                            jobData.status === 3 ? '生成成功' :
                                jobData.status === 4 ? '下载失败' :
                                    jobData.status === 5 ? '完全成功' : '未知'
              }}
            </el-tag>
          </el-descriptions-item>

          <!-- 任务类型 -->
          <el-descriptions-item label="生成方式">
            <el-tag :type="jobData.imageGen ? 'primary' : 'success'" size="large">
              {{ jobData.imageGen ? '图片生成' : '文本生成' }}
            </el-tag>
          </el-descriptions-item>

          <!-- 文本输入（仅文本生成） -->
          <el-descriptions-item label="文本描述" v-if="!jobData.imageGen">
            <div style="white-space: pre-wrap; font-size: 14px; color: #333;">
              {{ jobData.text }}
            </div>
          </el-descriptions-item>

          <!-- 图片输入（仅图片生成） -->
          <el-descriptions-item label="输入图片" v-if="jobData.imageGen">
            <div class="image-grid">
              <el-image
                  v-for="(item, index) in jobData.textObject"
                  :key="index"
                  :src="item.viewImageUrl"
                  fit="cover"
                  style="width: 100px; height: 100px; border-radius: 8px; margin-right: 8px; margin-bottom: 8px;"
                  :preview-src-list="jobData.textObject.map(i => i.viewImageUrl)"
                  :initial-index="index"
              />
            </div>
          </el-descriptions-item>

          <!-- 预览图 -->
          <el-descriptions-item label="预览图" v-if="jobData.status >= 3 && modelPreviewImageUrls.length > 0">
            <el-image
                :src="modelPreviewImageUrls[0]"
                fit="cover"
                style="width: 120px; height: 120px; border-radius: 8px;"
                :preview-src-list="modelPreviewImageUrls"
            />
          </el-descriptions-item>

          <!-- 创建时间 -->
          <el-descriptions-item label="创建时间">
      <span style="color: #666; font-size: 14px;">
        {{ formatDateTime(jobData.createdTime) }}
      </span>
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </div>
  </div>




</template>

<style scoped lang="scss">
// 按钮
.viewBtn{
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
}

.showCard{
  width: 18vw;
  height: 18vw;
}

.cardCenter{
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}

// 整体卡片样式
.model-card-wrapper {
  position: relative;
  display: inline-block; /* 紧凑布局 */
  border-radius: 8px;
  overflow: hidden;
  width: 17vw;
  margin: 15px 0;
  background-color: white;

  // 新增：边框和阴影
  border: 1px solid #e0e0e0; // 浅灰色边框
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); // 柔和的投影

  transition: box-shadow 0.3s ease; // 平滑过渡阴影
}
/* 按钮区域默认隐藏 */
.viewBtn {
  position: absolute;
  bottom: 10px;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: space-evenly;
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none; /* 防止未 hover 时点击 */
}

/* 当鼠标悬停在卡片上时显示按钮 */
.model-card-wrapper:hover .viewBtn {
  opacity: 1;
  pointer-events: auto; /* 可点击 */
}

// 右上角关闭按钮
.closeBtn {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s ease;
  /* 关键：确保能接收鼠标事件 */
  pointer-events: auto;
  /* 确保在最上层 */
  z-index: 10;
}

.model-card-wrapper:hover .closeBtn {
  opacity: 1;
}

.job-details-descriptions {
  :deep(.el-descriptions__label) {
    font-weight: 600;
    color: #333;
    font-size: 15px;
    background-color: #f8f9fa;
    padding: 12px 16px;
  }

  :deep(.el-descriptions__content) {
    padding: 12px 16px;
    font-size: 14px;
    color: #555;
  }

  :deep(.el-descriptions-item__cell) {
    padding: 0;
    border-bottom: 1px solid #ebeef5;
  }
}

// 图片网格布局
.image-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 4px;
}

// 对话框整体内边距
:deep(.el-dialog__body) {
  padding: 20px 24px;
}
</style>
